<template>
  <div class="job-detail">
    <div class="detail-header">
      <el-button @click="handleBack" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <div class="detail-content" v-if="jobDetail">
      <!-- 岗位基本信息 -->
      <el-card class="job-info-card">
        <div class="job-header">
          <div class="job-title-section">
            <h1 class="job-title">{{ jobDetail.title }}</h1>
            <div class="job-meta">
              <el-tag :type="getJobTypeTagType(jobDetail.job_type)" class="meta-tag">
                {{ getJobTypeText(jobDetail.job_type) }}
              </el-tag>
              <el-tag :type="getWorkModeTagType(jobDetail.work_mode)" class="meta-tag">
                {{ getWorkModeText(jobDetail.work_mode) }}
              </el-tag>
              <el-tag v-if="jobDetail.is_featured" type="danger" class="meta-tag">
                推荐岗位
              </el-tag>
            </div>
          </div>
          <div class="job-actions" v-if="userStore.userInfo?.role === 'student'">
            <el-button
              type="primary"
              size="large"
              @click="handleApply"
              :disabled="jobDetail.status !== 'published'"
            >
              申请岗位
            </el-button>
          </div>
          <div class="job-actions" v-else>
            <el-button @click="handleEdit">编辑岗位</el-button>
            <el-button
              v-if="jobDetail.status === 'draft'"
              type="success"
              @click="handlePublish"
            >
              发布岗位
            </el-button>
            <el-button
              v-if="jobDetail.status === 'published'"
              type="warning"
              @click="handleClose"
            >
              关闭岗位
            </el-button>
          </div>
        </div>

        <div class="job-summary">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="summary-item">
                <el-icon class="summary-icon"><OfficeBuilding /></el-icon>
                <div class="summary-content">
                  <div class="summary-label">公司</div>
                  <div class="summary-value">{{ jobDetail.company_info?.name }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <el-icon class="summary-icon"><Location /></el-icon>
                <div class="summary-content">
                  <div class="summary-label">工作地点</div>
                  <div class="summary-value">{{ jobDetail.work_location }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <el-icon class="summary-icon"><Money /></el-icon>
                <div class="summary-content">
                  <div class="summary-label">薪资</div>
                  <div class="summary-value">{{ jobDetail.salary_range }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-item">
                <el-icon class="summary-icon"><User /></el-icon>
                <div class="summary-content">
                  <div class="summary-label">招聘人数</div>
                  <div class="summary-value">{{ jobDetail.positions_available }}人</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-row :gutter="20">
        <!-- 左侧：岗位详细信息 -->
        <el-col :span="16">
          <!-- 职位描述 -->
          <el-card class="detail-section">
            <template #header>
              <h3>职位描述</h3>
            </template>
            <div class="content-text">
              {{ jobDetail.description }}
            </div>
          </el-card>

          <!-- 岗位职责 -->
          <el-card class="detail-section">
            <template #header>
              <h3>岗位职责</h3>
            </template>
            <div class="content-text">
              {{ jobDetail.responsibilities }}
            </div>
          </el-card>

          <!-- 任职要求 -->
          <el-card class="detail-section">
            <template #header>
              <h3>任职要求</h3>
            </template>
            <div class="content-text">
              {{ jobDetail.requirements }}
            </div>
          </el-card>

          <!-- 福利待遇 -->
          <el-card class="detail-section" v-if="jobDetail.benefits">
            <template #header>
              <h3>福利待遇</h3>
            </template>
            <div class="content-text">
              {{ jobDetail.benefits }}
            </div>
          </el-card>

          <!-- 技能要求 -->
          <el-card class="detail-section" v-if="jobDetail.required_skills || jobDetail.preferred_skills">
            <template #header>
              <h3>技能要求</h3>
            </template>
            <div class="skills-section">
              <div v-if="jobDetail.required_skills" class="skill-group">
                <h4>必备技能</h4>
                <div class="skill-tags">
                  <el-tag
                    v-for="skill in jobDetail.required_skills.split(',')"
                    :key="skill"
                    type="danger"
                    class="skill-tag"
                  >
                    {{ skill.trim() }}
                  </el-tag>
                </div>
              </div>
              <div v-if="jobDetail.preferred_skills" class="skill-group">
                <h4>优先技能</h4>
                <div class="skill-tags">
                  <el-tag
                    v-for="skill in jobDetail.preferred_skills.split(',')"
                    :key="skill"
                    type="success"
                    class="skill-tag"
                  >
                    {{ skill.trim() }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧：公司信息和其他信息 -->
        <el-col :span="8">
          <!-- 公司信息 -->
          <el-card class="company-info-card">
            <template #header>
              <h3>公司信息</h3>
            </template>
            <div class="company-info" v-if="jobDetail.company_info">
              <div class="company-logo" v-if="jobDetail.company_info.logo">
                <img :src="jobDetail.company_info.logo" :alt="jobDetail.company_info.name" />
              </div>
              <div class="company-details">
                <h4>{{ jobDetail.company_info.name }}</h4>
                <div class="company-meta">
                  <p><strong>行业：</strong>{{ jobDetail.company_info.industry }}</p>
                  <p><strong>规模：</strong>{{ getCompanySizeText(jobDetail.company_info.company_size) }}</p>
                  <p><strong>类型：</strong>{{ getCompanyTypeText(jobDetail.company_info.company_type) }}</p>
                  <p v-if="jobDetail.company_info.website">
                    <strong>网站：</strong>
                    <el-link :href="jobDetail.company_info.website" target="_blank" type="primary">
                      {{ jobDetail.company_info.website }}
                    </el-link>
                  </p>
                </div>
                <div class="company-description" v-if="jobDetail.company_info.description">
                  <h5>公司简介</h5>
                  <p>{{ jobDetail.company_info.description }}</p>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 岗位信息 -->
          <el-card class="job-meta-card">
            <template #header>
              <h3>岗位信息</h3>
            </template>
            <div class="job-meta-info">
              <div class="meta-item">
                <span class="meta-label">学历要求：</span>
                <span class="meta-value">{{ jobDetail.education_requirement || '不限' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">经验要求：</span>
                <span class="meta-value">{{ jobDetail.experience_requirement || '不限' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">所属部门：</span>
                <span class="meta-value">{{ jobDetail.department || '未指定' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">远程工作：</span>
                <span class="meta-value">{{ jobDetail.remote_allowed ? '支持' : '不支持' }}</span>
              </div>
              <div class="meta-item" v-if="jobDetail.application_deadline">
                <span class="meta-label">申请截止：</span>
                <span class="meta-value">{{ formatDate(jobDetail.application_deadline) }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">发布时间：</span>
                <span class="meta-value">{{ formatDate(jobDetail.published_at) }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">发布人：</span>
                <span class="meta-value">{{ jobDetail.published_by_name }}</span>
              </div>
            </div>
          </el-card>

          <!-- 联系方式 -->
          <el-card class="contact-card">
            <template #header>
              <h3>联系方式</h3>
            </template>
            <div class="contact-info">
              <div class="contact-item">
                <el-icon><Message /></el-icon>
                <span>{{ jobDetail.contact_email }}</span>
              </div>
              <div class="contact-item" v-if="jobDetail.contact_phone">
                <el-icon><Phone /></el-icon>
                <span>{{ jobDetail.contact_phone }}</span>
              </div>
              <div class="contact-item" v-if="jobDetail.company_info?.address">
                <el-icon><Location /></el-icon>
                <span>{{ jobDetail.company_info.address }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="岗位不存在或已被删除" />
    </div>

    <!-- 申请岗位对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      title="申请岗位"
      width="600px"
      @close="resetApplyForm"
    >
      <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="100px">
        <el-form-item label="岗位信息">
          <div class="apply-job-info">
            <h4>{{ jobDetail?.title }}</h4>
            <p>{{ jobDetail?.company_info?.name }} - {{ jobDetail?.work_location }}</p>
            <p>薪资：{{ jobDetail?.salary_range }}</p>
          </div>
        </el-form-item>
        <el-form-item label="求职信" prop="cover_letter">
          <el-input
            v-model="applyForm.cover_letter"
            type="textarea"
            :rows="4"
            placeholder="请简要介绍您的求职意向和优势..."
          />
        </el-form-item>
        <el-form-item label="简历文件">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            accept=".pdf,.doc,.docx"
            :on-change="handleFileChange"
          >
            <el-button>选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 PDF、DOC、DOCX 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApplication" :loading="submitting">
          提交申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, OfficeBuilding, Location, Money, User,
  Message, Phone
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { jobApi } from '@/api/jobs'
import type { Job } from '@/types'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const jobDetail = ref<Job | null>(null)
const applyDialogVisible = ref(false)
const applyFormRef = ref()
const uploadRef = ref()

// 申请表单
const applyForm = reactive({
  cover_letter: '',
  resume_file: null as File | null
})

const applyRules = {
  cover_letter: [
    { required: true, message: '请填写求职信', trigger: 'blur' }
  ]
}

// 方法
const fetchJobDetail = async () => {
  const jobId = route.params.id
  if (!jobId) {
    router.push('/jobs/list')
    return
  }

  loading.value = true
  try {
    const response = await jobApi.getJobDetail(Number(jobId))
    jobDetail.value = response.data
  } catch (error) {
    console.error('获取岗位详情失败:', error)
    ElMessage.error('获取岗位详情失败')
    jobDetail.value = null
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  router.back()
}

const handleEdit = () => {
  if (jobDetail.value) {
    router.push(`/jobs/${jobDetail.value.id}/edit`)
  }
}

const handlePublish = async () => {
  if (!jobDetail.value) return

  try {
    await jobApi.publishJob(jobDetail.value.id)
    ElMessage.success('岗位发布成功')
    fetchJobDetail()
  } catch (error) {
    console.error('发布岗位失败:', error)
    ElMessage.error('发布岗位失败')
  }
}

const handleClose = async () => {
  if (!jobDetail.value) return

  try {
    await jobApi.closeJob(jobDetail.value.id)
    ElMessage.success('岗位关闭成功')
    fetchJobDetail()
  } catch (error) {
    console.error('关闭岗位失败:', error)
    ElMessage.error('关闭岗位失败')
  }
}

const handleApply = () => {
  applyDialogVisible.value = true
}

const handleFileChange = (file: any) => {
  applyForm.resume_file = file.raw
}

const resetApplyForm = () => {
  applyForm.cover_letter = ''
  applyForm.resume_file = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const submitApplication = async () => {
  if (!applyFormRef.value || !jobDetail.value) return

  try {
    await applyFormRef.value.validate()

    submitting.value = true

    const formData = new FormData()
    formData.append('cover_letter', applyForm.cover_letter)
    if (applyForm.resume_file) {
      formData.append('resume_file', applyForm.resume_file)
    }

    await jobApi.applyJob(jobDetail.value.id, formData)

    ElMessage.success('申请提交成功')
    applyDialogVisible.value = false
    resetApplyForm()

  } catch (error) {
    console.error('提交申请失败:', error)
    ElMessage.error('提交申请失败')
  } finally {
    submitting.value = false
  }
}

// 辅助方法
const getJobTypeText = (type: string) => {
  const map: Record<string, string> = {
    full_time: '全职',
    part_time: '兼职',
    internship: '实习',
    contract: '合同工',
    remote: '远程工作'
  }
  return map[type] || type
}

const getJobTypeTagType = (type: string) => {
  const map: Record<string, string> = {
    full_time: 'primary',
    part_time: 'success',
    internship: 'warning',
    contract: 'info',
    remote: 'danger'
  }
  return map[type] || 'info'
}

const getWorkModeText = (mode: string) => {
  const map: Record<string, string> = {
    online: '线上',
    offline: '线下',
    hybrid: '混合'
  }
  return map[mode] || mode
}

const getWorkModeTagType = (mode: string) => {
  const map: Record<string, string> = {
    online: 'primary',
    offline: 'success',
    hybrid: 'warning'
  }
  return map[mode] || 'info'
}

const getCompanyTypeText = (type: string) => {
  const map: Record<string, string> = {
    startup: '初创公司',
    sme: '中小企业',
    large: '大型企业',
    multinational: '跨国公司',
    government: '政府机构',
    ngo: '非营利组织'
  }
  return map[type] || type
}

const getCompanySizeText = (size: string) => {
  const map: Record<string, string> = {
    '1-10': '1-10人',
    '11-50': '11-50人',
    '51-200': '51-200人',
    '201-500': '201-500人',
    '501-1000': '501-1000人',
    '1000+': '1000人以上'
  }
  return map[size] || size
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  fetchJobDetail()
})
</script>

<style lang="scss" scoped>
.job-detail {
  .detail-header {
    margin-bottom: 20px;

    .back-btn {
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }

  .job-info-card {
    margin-bottom: 20px;

    .job-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 30px;

      .job-title-section {
        flex: 1;

        .job-title {
          margin: 0 0 15px 0;
          font-size: 28px;
          font-weight: 600;
          color: #303133;
        }

        .job-meta {
          display: flex;
          gap: 10px;
          flex-wrap: wrap;

          .meta-tag {
            font-size: 12px;
          }
        }
      }

      .job-actions {
        flex-shrink: 0;
        margin-left: 20px;
      }
    }

    .job-summary {
      .summary-item {
        display: flex;
        align-items: center;
        padding: 15px;
        background-color: #f8f9fa;
        border-radius: 8px;

        .summary-icon {
          font-size: 24px;
          color: #409eff;
          margin-right: 12px;
        }

        .summary-content {
          .summary-label {
            font-size: 12px;
            color: #909399;
            margin-bottom: 4px;
          }

          .summary-value {
            font-size: 14px;
            font-weight: 600;
            color: #303133;
          }
        }
      }
    }
  }

  .detail-section {
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      color: #303133;
    }

    .content-text {
      line-height: 1.8;
      color: #606266;
      white-space: pre-wrap;
    }

    .skills-section {
      .skill-group {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        h4 {
          margin: 0 0 10px 0;
          font-size: 16px;
          color: #303133;
        }

        .skill-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;

          .skill-tag {
            font-size: 12px;
          }
        }
      }
    }
  }

  .company-info-card,
  .job-meta-card,
  .contact-card {
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 16px;
      color: #303133;
    }
  }

  .company-info {
    .company-logo {
      text-align: center;
      margin-bottom: 15px;

      img {
        max-width: 100px;
        max-height: 100px;
        border-radius: 8px;
      }
    }

    .company-details {
      h4 {
        margin: 0 0 15px 0;
        font-size: 18px;
        color: #303133;
        text-align: center;
      }

      .company-meta {
        p {
          margin: 8px 0;
          font-size: 14px;
          color: #606266;

          strong {
            color: #303133;
          }
        }
      }

      .company-description {
        margin-top: 15px;

        h5 {
          margin: 0 0 8px 0;
          font-size: 14px;
          color: #303133;
        }

        p {
          margin: 0;
          font-size: 13px;
          color: #606266;
          line-height: 1.6;
        }
      }
    }
  }

  .job-meta-info {
    .meta-item {
      display: flex;
      justify-content: space-between;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .meta-label {
        font-size: 14px;
        color: #909399;
      }

      .meta-value {
        font-size: 14px;
        color: #303133;
        font-weight: 500;
      }
    }
  }

  .contact-info {
    .contact-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      .el-icon {
        margin-right: 8px;
        color: #409eff;
      }

      span {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .loading-container,
  .error-container {
    padding: 40px;
    text-align: center;
  }

  .apply-job-info {
    h4 {
      margin: 0 0 8px 0;
      color: #303133;
    }

    p {
      margin: 4px 0;
      color: #606266;
      font-size: 14px;
    }
  }
}
</style>